<template>
  <div>Child</div>
  <p>{{ formState.username }}</p>
  <p>{{ price }}</p>
  <p>{{ count }}</p>
  <button @click="update">update</button>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  computed,
  watch,
  onBeforeMount,
  onMounted,
  onUpdated,
  onBeforeUnmount,
} from "vue";

interface FormState {
  username: string;
  password: string;
}

export default defineComponent({
  name: "Child",
  // setup函数一上来就会触发，相当于beforeCreate和created
  setup(props, context) {
    /*
      ref 定义单个响应式数据
      reactive 定义多个响应式数据
    */

    // 定义响应式数据
    const num = ref<number>(0);
    const count = ref<number>(0);
    const formState = reactive<FormState>({
      username: "aa",
      password: "bb",
    });

    // 生命周期函数
    onMounted(() => {
      console.log("mounted", props.age);
      // 触发自定义事件
      context.emit("say");
    });

    onUpdated(() => {
      console.log("updated");
    });

    // 定义methods
    const update = () => {
      count.value++;
    };

    // 定义计算属性
    // 只读
    const price = computed(() => {
      return num.value + "元";
    });
    // 可读可写
    // computed({
    //   get() {},
    //   set(val) {}
    // });

    // 定义监视属性
    watch(
      count,
      (newVal, oldVal) => {
        console.log("watch触发了");
      },
      // opitons
      { immediate: true, deep: true }
    );

    return {
      num,
      count,
      formState,
      price,
      update,
    };
  },
  // 声明接受props
  props: {
    age: {
      type: Number,
      required: true,
    },
  },
  // 声明接受事件
  emits: ["say"],
  components: {},
  directives: {},
});
</script>
